var transDataCalls = 0;

$(document).ready(function(){
	
	$("#msgDlg").css('font-size', '0.8em');
	$("#msgDlg").dialog( {
		bgiframe :true,
		autoOpen :false,
		modal :true,
		buttons : {
			Ok : function() {
				$(this).dialog('close');
			}
		}
	});
	
	$("#newCatDlg").dialog( {
		bgiframe :true,
		autoOpen :false,
		modal :true,
		buttons : {
			Cancel : function(){
				$(this).dialog('close');
			},
			Ok : function() {
				if ($("input:radio[name='catType']:checked").attr("value") == null) {
					alert("Select category type.");
				} else	if ($("input:radio[name='catType']:checked").attr("value") == "expense"){
					saveCategory($("#newCategory").val(), "1");
					clearCategories();
					$(this).dialog('close');
				} else if ($("input:radio[name='catType']:checked").attr("value") == "income"){
					saveCategory($("#newCategory").val(), "0");
					clearCategories();
					$(this).dialog('close');
				}
				$("#newCategory").attr("value", "");
			}
		}
	});
	
	
	$("#uploadBtn").click(function(){
		$("#fileUploadContainer").dialog("open");
	});
	
	
	if ($("#transactionViewSelect").val() == "all"){
		$("#transactionView").val("all");
	} else if ($("#transactionViewSelect").val() == "unreconciled"){
		$("#transactionView").val("unreconciled");
	} else if ($("#transactionViewSelect").val() == "past3months"){
		$("#transactionView").val("past3months");
	} else if ($("#transactionViewSelect").val() == "thisMonth"){
		$("#transactionView").val("thisMonth");
	}

	$("#confirmDlg").css('font-size', '0.8em');
	$("#confirmDlg").dialog( {
		bgiframe :true,
		autoOpen :false,
		modal :true,
		buttons : {
			"Cancel": function() {
				$(this).dialog('close');
			},
			"Yes" : function() {
				deleteTransaction();
				$(this).dialog('close');
			}
		}
	});
	
	$("#fileUploadContainer").dialog( {
		bgiframe :true,
		autoOpen :false,
		autoOpen :false,
		width: 500,
		modal :true,
		buttons : {
			"Cancel": function() {
				$(this).dialog('close');
			},
			"Upload" : function() {
				readStatement();
				$(this).dialog('close');
			}
		}
	});
	
	
	if (getUrlVars()["showSearch"] == "true"){
		$("#searchPanel").show();
	}
	
	formatAmounts();
	
	$("#OFXAvailableAmountTR").hide();
	
	$("input[name=uploadStatementType]").click(function(){
		if($(this).val() == "OFX"){ 
			$("#OFXAvailableAmountTR").show();
		}
		else{
			$("#OFXAvailableAmountTR").hide();
		}
	});
	
});

function formatAmounts(){
	$(".rowRow").each(function(){
		var amountCol = $(this).find(".rowAmount");
		var amount = $(amountCol).html().split(" ");
		$(amountCol).html("R "+ formatCurrency(eval(amount[1]).toFixed(2)));
		
		var runningBalanceCol = $(this).find(".runningBalance");
		amount = $(runningBalanceCol).html().split(" ");
		$(runningBalanceCol).html("R "+ formatCurrency(eval(amount[1]).toFixed(2)));
	});
	
	$("#totalAmount").html("R "+ formatCurrency($("#totalAmount").html()));
}

function doFilter(){
	$(".rowRow").each(function(){
		var string1 = $(this).find(".rowDescription").find("a").html().toLowerCase();
		var string2 = $("#searchCriteria").val().toLowerCase();
		if (string1.indexOf(string2) == -1){
			$(this).hide();
		} else {
			$(this).show();
		}
	});
}

function showSearch(){
	if ($("#searchPanel").is(":hidden")){
		$("#searchPanel").fadeIn("normal");
	} else {
		$("#searchPanel").fadeOut("normal");
	}
}


function confirmDeleteTransaction(){
	$("#confirmDlg").html("Are you sure you want to delete this transaction?");
	$("#confirmDlg").dialog("open");
}

function deleteTransaction(){
	var url="/index.php?mod=controller1";
	var parms = new Object();
	parms["action"]= "deleteTransaction";
	parms["transactionId"]= $("input:radio[name:'selectTransaction']:checked").val();
	$.post(url,parms,function(resultData){
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			$("#msgDlg").html("Transaction successfully deleted.");
			$("#msgDlg").dialog("open");
			updateTransactionView();
		} else {
			alert($(resultData).find("errMessage").text());
		}
		

	});
}

function updateTransactionView(){
	showLoading(true);
	if ($("#transactionView").val() == "first20"){
		top.location = "/index.php?mod=transactionView&accId="+ $("#accountId").val()+"&showSearch="+ $("#searchPanel").is(":visible");
	} else if ($("#transactionView").val() == "all"){
		top.location = "/index.php?mod=transactionView&accId="+ $("#accountId").val()+"&transactionView=all&showSearch="+ $("#searchPanel").is(":visible");;
	} else if ($("#transactionView").val() == "unreconciled"){
		top.location = "/index.php?mod=transactionView&accId="+ $("#accountId").val()+"&transactionView=unreconciled&showSearch="+ $("#searchPanel").is(":visible");
	} else if ($("#transactionView").val() == "past3months"){
		top.location = "/index.php?mod=transactionView&accId="+ $("#accountId").val()+"&transactionView=past3months&showSearch="+ $("#searchPanel").is(":visible");
	} else if ($("#transactionView").val() == "thisMonth"){
		top.location = "/index.php?mod=transactionView&accId="+ $("#accountId").val()+"&transactionView=thisMonth&showSearch="+ $("#searchPanel").is(":visible");
	}
}

function updateDescription(){
	if ($("#transDescription").val() == ""){
		$("#transDescription").val($.trim($("#catSel option:selected").text()));
	}
}

function createNewTransaction(){
	$("#demoContainer").dialog({
		bgiframe :true,
		autoOpen :false,
		width: 500,
		maxHeight: 200,
		modal :true,
		buttons : {
			Save : function() {
				saveTransaction();
				$("#transDate").datepicker("destroy");
				$(this).dialog('destroy');
			},
			Cancel : function() {
				$("#transDate").datepicker("destroy");
				$(this).dialog('destroy');
			}
		},
		 open: function(event, ui) {
			var now = new Date();
			$("#transDate").val(now.formatDate("yyyy-MM-dd"));
			$("#transDate").datepicker({ dateFormat: 'yy-mm-dd'}); 
		},
		close : function(event, ui){
			$("#transDate").datepicker("destroy");
		}
	});
	
	$("#transDescription").val("");
	$("#bankRef").html("");
	$("#transDescriptor").val("");
	$("#transAmount").val("");
	$("#currentTransId").val("");
		
	populateCategories();
	
	$("#demoContainer").dialog("open");
	$("#transAmount").focus();
}

function populateCategories(){
	$(".catRow").remove();
	fetchCategories("budgetitem");
	fetchCategories("accounts");
}

function fetchCategories(type){
	var action = "";
	if (type == "budgetitem"){
		action = "getAllBudgetItems";
	} else if (type == "accounts"){
		action = "getAccountsAsBudgetItems";
	}
	
	var url="/index.php?mod=controller1";
	var parms = new Object();
	parms["action"]= action;
	$.post(url,parms,function(resultData){
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			updateCategories(resultData);	
			
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function saveTransaction(){
	var url="/index.php?mod=controller1";
	var parms = new Object();
	parms["action"]= "saveTransaction";
	parms["accId"]= $("#accountId").val();
	parms["transId"]= $("#currentTransId").val();
	parms["transDate"]= $("#transDate").val();
	parms["transDescription"]= $("#transDescription").val();
	parms["autoReconcile"]= $("#autoReconcileCB").attr("checked");
	parms["transDescriptor"]= $("#transDescriptor").val();
	parms["categoryId"]= $("#"+$("#catSel").val()).attr("categoryId");
	parms["budgetItemId"]= $("#catSel").val();
	parms["reconciled"]= 1;
	parms["transAmount"] = $("#transAmount").val();
	parms["enterCreditOrDebit"] = $(":radio[name='txType']:checked").val();
	parms["confirmTransInsert"] = $("#confirmTransInsert").val();
	
	if ($("input:radio[name='transactionType']:checked").val() == "debit"){
		parms["transAmount"] = $("#transAmount").val() * -1;
	}
	
	$.post(url,parms,function(resultData){
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			updateTransactionView();
		} else {
			if ($(resultData).find("code").text() == "026"){
				confirmTransactionInsert(resultData);
				return;
			}
			alert($(resultData).find("errMessage").text());
		}
	});
}

function confirmTransactionInsert(data){
	$("#confirmDlg").html($(data).find("errMessage").text());
	var table = "<table width='100%'>";
	$(data).find("Transaction").each(function(){
		table += "<tr><td width='100'>"+ $(this).find("date").text() +"</td><td>"+ $(this).find("description").text() +"</td><td> R"+ $(this).find("amount").text() +"</td></tr>";
	});
	$("#confirmDlg").append("<br/><br/>");
	$("#confirmDlg").append(table+"</table>");
	
	$("#confirmDlg").dialog( {
		bgiframe :true,
		autoOpen :false,
		width: "400",
		modal :true,
		buttons : {
			"Cancel": function() {
				$(this).dialog('close');
			},
			"No": function() {
				$("#confirmTransInsert").val("false");
				saveTransaction();
				$(this).dialog('close');
			},
			"Yes" : function() {
				$("#confirmTransInsert").val("true");
				saveTransaction();
				$(this).dialog('close');
			}
		}
	});
	$("#confirmDlg").dialog('open');
}


function clearCategories(){
	$("#catSel").find("option[id!='expenses'][id!='income']").each(function(){
		$(this).remove();
	});
	updated = false;
}

function readStatement(){
	$("#fileUploadForm").find("#action").val($("#accountId").val());
	$("#accId").val($("#accountId").val());
	$("#fileUploadForm").ajaxSubmit({
			success: function(resultData) { 
				var errorCode = $(resultData).find("code").text();
				
				if(errorCode == 0){
					updateTransData(resultData);
					updateTransactionView();
				} else if(errorCode == 1) {
					$("#msgDlg").html("There was a database error. Askies.");
					$("#msgDlg").dialog("open");
				}
				else if(errorCode == 2){
					$("#msgDlg").html("The statement uploaded is not for this account");
					$("#msgDlg").dialog("open");
				}
		    } 
	}); 

}

function openContainer(id){
	$("#transLoadingImg").show();
	transDataCalls = 2;
	$("#currentTransId").attr("value", id);
		
	$("#demoContainer").dialog({
		bgiframe :true,
		autoOpen :false,
		width: 500,
		maxHeight: 200,
		modal :true,
		buttons : {
			Save : function() {
				saveTransaction();
				$("#transDate").datepicker("destroy");
				$(this).dialog('destroy');
			},
			Cancel : function() {
				$("#transDate").datepicker("destroy");
				$(this).dialog('destroy');
			}
		},
		 open: function(event, ui) {
			$("#transDate").datepicker({ dateFormat: 'yy-mm-dd' }); 
		},
		close : function(event, ui){
			$("#transDate").datepicker("destroy");
		}
	});
		
	getDataForTransaction(id);
	
	$("#demoContainer").dialog("open");
	$("#transAmount").focus();
}

function disableAutoRecon(){
	if ($("#autoReconcileCB").attr("checked") == true){
		$("#transDescriptor").attr("disabled", false);
	} else if ($("#autoReconcileCB").attr("checked") == false){ 
		$("#transDescriptor").attr("disabled", true);	
	}
}

var cb = function(id){
	
	var url="/index.php?mod=controller1";
	var parms = new Object();
	parms["action"]= "getTransaction";
	parms["transId"]= id;
	
	
	$.post(url,parms,function(resultData){
		var errorCode = $(resultData).find("code").text();
		if(errorCode == 0){
			updateTransData(resultData);
		} else if(errorCode == 1) {
			$("#msgDlg").html("There was a database error. Askies.");
			$("#msgDlg").dialog("open");
		} else if(errorCode == 2) {
			$("#msgDlg").html("Budget already Exists. Choose another month and year combination.");
			$("#msgDlg").dialog("open");
		}
	});
};

function getDataForTransaction(id){
	//$("#transferOptions").hide();
	//$("#enterTx").removeAttr("checked");
	populateCategories();
	setTimeout("cb("+id+");", 500);
}

function updateCategories(resultData){
	$(resultData).find("BudgetItem").each(function(){
		if ($.trim($(this).find("categoryId").text()) == "2"){
			$("<option show='"+ $(this).find("existInCurrentBudget").text() +"' class='catRow' categoryId='2' id='"+ $.trim($(this).find("id").text()) +"' value='"+ $.trim($(this).find("id").text()) +"'>&nbsp;&nbsp;&nbsp;"+$.trim($(this).find("description").text())+"</option>").insertAfter($("#varExpenses"));
		} else if ($.trim($(this).find("categoryId").text()) == "3"){
			$("<option show='"+ $(this).find("existInCurrentBudget").text() +"' class='catRow' categoryId='3' id='"+ $.trim($(this).find("id").text()) +"' value='"+ $.trim($(this).find("id").text()) +"'>&nbsp;&nbsp;&nbsp;"+$.trim($(this).find("description").text())+"</option>").insertAfter($("#fixedExpenses"));
		}  else if ($.trim($(this).find("categoryId").text()) == "4"){
			$("<option show='"+ $(this).find("existInCurrentBudget").text() +"' class='catRow' categoryId='4' id='"+ $.trim($(this).find("id").text()) +"' value='"+ $.trim($(this).find("id").text()) +"'>&nbsp;&nbsp;&nbsp;"+$.trim($(this).find("description").text())+"</option>").insertAfter($("#savingsExpenses"));
		}  else if ($.trim($(this).find("categoryId").text()) == "1"){
				$("<option show='"+ $(this).find("existInCurrentBudget").text() +"' class='catRow' categoryId='1' id='"+ $.trim($(this).find("id").text()) +"' value='"+ $.trim($(this).find("id").text()) +"'>&nbsp;&nbsp;&nbsp;"+$.trim($(this).find("description").text())+"</option>").insertAfter($("#income"));
		} else if ($.trim($(this).find("categoryId").text()) == "6"){
			//we need to remove the current account. we cant tranfer to same account.
			if ($("#accountId").val() != $.trim($(this).find("id").text())){
				$("<option class='catRow' categoryId='6' id='"+ $.trim($(this).find("id").text()) +"' value='"+ $.trim($(this).find("id").text()) +"'>&nbsp;&nbsp;&nbsp;"+$.trim($(this).find("description").text())+"</option>").insertAfter($("#transfer"));
			}
		}
		
	});
	//$("input:radio[name='transactionType']:nth(0)").attr("checked","checked");
	$("#catSel").val(currentBudgetId);
	
	$(".catRow").each(function(){
		if ($(this).attr("show") == "false"){
			$(this).hide();
		}
	});
	
	if (--transDataCalls == 0){
		$("#transLoadingImg").fadeOut("normal");
	}
}

function toggleUnusedCategories(){
	$(".catRow").each(function(){
		if ($(this).attr("show") == "false"){
			$(this).toggle();
		}
	});
}

var currentBudgetId;

function updateTransData(resultData){
	currentBudgetId = $.trim($(resultData).find("budgetitemid").text());
	$("#catSel").val(currentBudgetId);
	$("#transDescription").attr("value", $.trim($(resultData).find("description").text().replace(/\\/g, "")));
	$("#transDate").attr("value", $.trim($(resultData).find("date").text()));
	$("#transAmount").attr("value", $.trim($(resultData).find("amount").text()));
	$("#bankRef").html($.trim($(resultData).find("bankRef").text()));
	$("#transDescriptor").attr("value", $.trim($(resultData).find("bankRef").text()));
	$("#currentTransType").val($.trim($(resultData).find("type").text()));
	
	
	if ($.trim($(resultData).find("type").text()) == "income"){
		$("input:radio[name='transactionType']:nth(1)").attr("checked","checked");
		$("input:radio[name='txType']:nth(0)").attr("checked","checked");
	} else if ($.trim($(resultData).find("type").text()) == "expense"){
		$("input:radio[name='transactionType']:nth(0)").attr("checked","checked");
		$("input:radio[name='txType']:nth(1)").attr("checked","checked");
	}

}

function createNewCat(){
	$("#newCatDlg").dialog("option", "title", "New Category");
	$("#newCatDlg").dialog("open");
	$("#newCategory").focus();
}